<template>
  <div class="app-container home">
    <!-- 系统概览和实时告警列表放在同一排 -->
    <el-row :gutter="20">
      <!-- 系统概览 - 改为两行布局 -->
      <el-col :sm="24" :lg="6">
        <el-card style="max-height: 290px; min-height: 290px;">
          <div slot="header" class="clearfix" style="min-height: 26px">
            <span class="fun-title">电梯火警监测系统</span>
          </div>
          <el-row style="margin: -10px 0 5px 0; padding: 0;">
            <el-col :span="24">
              <p class="description">系统概述：本系统为智能化电梯火警监测平台，集成多楼宇实时数据采集、动态分析与预警处理，保障大容量运行安全，实现精准监控与高效响应。</p>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8" style="margin-bottom: 10px;">
              <div class="stat-card">
                <div class="stat-value">{{ overviewData.deviceCount }}-{{ overviewData.channelCount }}</div>
                <div class="stat-label">设备-通道</div>
              </div>
            </el-col>
            <el-col :span="8" style="margin-bottom: 10px;">
              <div class="stat-card warning" v-if="overviewData.maxTemperature > 60">
                <div class="stat-value warning">{{ overviewData.maxTemperature }}</div>
                <div class="stat-label">最高温度</div>
              </div>
              <div class="stat-card" v-else>
                <div class="stat-value">{{ overviewData.maxTemperature }}</div>
                <div class="stat-label">最高温度</div>
              </div>
            </el-col>
            <el-col :span="8" style="margin-bottom: 10px;">
              <div class="stat-card warning" v-if="overviewData.minTemperature > 60">
                <div class="stat-value warning">{{ overviewData.minTemperature }}</div>
                <div class="stat-label">最低温度</div>
              </div>
              <div class="stat-card" v-else>
                <div class="stat-value">{{ overviewData.minTemperature }}</div>
                <div class="stat-label">最低温度</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card warning" v-if="overviewData.temperatureAlarmCount > 0">
                <div class="stat-value warning">{{ overviewData.temperatureAlarmCount }}</div>
                <div class="stat-label">温度告警</div>
              </div>
              <div class="stat-card" v-else>
                <div class="stat-value">0</div>
                <div class="stat-label">温度告警</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card warning" v-if="overviewData.fiberAlarmCount > 0">
                <div class="stat-value warning">{{ overviewData.fiberAlarmCount }}</div>
                <div class="stat-label">断纤告警</div>
              </div>
              <div class="stat-card" v-else>
                <div class="stat-value">0</div>
                <div class="stat-label">断纤告警</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card warning" v-if="overviewData.laserFaultCount > 0">
                <div class="stat-value warning">{{ overviewData.laserFaultCount }}</div>
                <div class="stat-label">激光器故障</div>
              </div>
              <div class="stat-card" v-else>
                <div class="stat-value">0</div>
                <div class="stat-label">激光器故障</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 实时告警列表 - 占据更宽空间 -->
      <el-col :sm="24" :lg="18">
        <el-card style="min-height: 290px; max-height: 290px;">
          <div slot="header" class="clearfix" style="padding:0;">
            <span class="fun-title">实时告警列表</span>
            <!-- 查询条件 - 紧凑布局 -->
            <div style="float: right; margin-top: -2px;">
              <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" class="compact-form">
                <el-form-item label="告警类型" prop="alarmType" style="margin-bottom: 0;">
                  <el-select
                    v-model="queryParams.alarmType"
                    placeholder="全部类型"
                    style="width: 100px"
                    @change="handleQuery"
                  >
                    <el-option
                      v-for="dict in dict.type.alarm_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间" style="margin-bottom: 0;">
                  <el-date-picker
                    v-model="dateRange"
                    style="width: 200px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始"
                    end-placeholder="结束"
                    @change="handleQuery"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item style="margin-bottom: 0;">
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="alarmList"
            style="width: 100%"
            size="mini"
            height="190"
          >
            <el-table-column label="事件id" align="center" prop="id" width="70" />
            <el-table-column label="告警类型" align="center" prop="alarmType" width="80">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.alarm_type" :value="scope.row.alarmType"/>
              </template>
            </el-table-column>
            <el-table-column label="设备&通道" align="center" prop="deviceNo" width="90">
              <template slot-scope="scope">
                <span>{{ scope.row.deviceNo }}-{{ scope.row.chanel }}</span>
              </template>
            </el-table-column>
            <el-table-column label="位置" align="center" prop="lcName" v-if="(queryParams.alarmType == '' || queryParams.alarmType==3)" width="260" />
            <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==3)" label="米标" align="center" prop="meterMark" width="70"/>
            <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==1)" label="断纤告警位置" align="center" prop="fiberBreakPosition" width="100"/>
            <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==2)" label="激光器温度" align="center" prop="laserTemperature" width="100"/>

            <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==3)" label="温温" align="center" prop="maxTemperature" width="80">
              <template slot-scope="scope">
                {{scope.row.maxTemperature}}-{{ scope.row.minTemperature }}
              </template>
            </el-table-column>

            <el-table-column label="数量" align="center" prop="alarmCount" width="70">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click="handleViewRecords(scope.row)"
                >{{ scope.row.alarmCount }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="eventStatus" width="70">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.alarm_state" :value="scope.row.eventStatus" size="mini"/>
              </template>
            </el-table-column>
            <el-table-column label="告警开始时间" align="center" prop="alarmStartTime" width="150">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.alarmStartTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <!-- 已处理的事件不显示处理按钮 -->
                <el-button
                  v-if="scope.row.eventStatus !== 2"
                  size="mini"
                  type="text"
                  icon="el-icon-check"
                  @click="handleSingleHandle(scope.row)"
                  v-hasPermi="['project:event:handle']"
                >处理</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            :small="true"
            layout="prev, pager, next"
            @pagination="getList"
            style="padding: 14px 0 0 0; margin: -10px 0 0 0;"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 楼栋电梯监测卡片 -->
    <div class="monitor-section" style="margin: 16px 0 0 0;">
      <div class="section-title">楼栋电梯状态监测</div>
      <el-row :gutter="15">
        <el-col
          v-for="building in buildingData"
          :key="building.lcId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          style="margin-bottom: 15px;"
        >
          <el-card class="building-card" :class="{ 'has-alarm': building.monitorStatus.status === 2 }" shadow="hover" body-style="padding: 12px;">
            <div class="clearfix building-header">
              <span class="building-name">{{ building.levelName }}</span>
              <el-tag
                v-if="building.monitorStatus.status === 2"
                type="danger"
                size="mini"
              >
                告警
              </el-tag>
              <el-tag
                v-else
                type="success"
                size="mini"
              >
                正常
              </el-tag>
            </div>

            <!-- 遍历单元 -->
            <div v-for="unit in getUnitsByBuilding(building.lcCode)" :key="unit.lcId" class="unit-section">
              <el-row :gutter="8" align="middle">
                <!-- 竖着写的单元名称 -->
                <el-col :span="3">
                  <div class="unit-name vertical-text">{{ unit.levelName }}</div>
                </el-col>

                <!-- 电梯列表 -->
                <el-col :span="21">
                  <el-row :gutter="8" class="elevator-list">
                    <el-col
                      v-for="elevator in getElevatorsByUnit(unit.lcCode)"
                      :key="elevator.lcId"
                      :span="12"
                      style="margin-bottom: 8px;"
                    >
                      <div
                        class="elevator-item"
                        :class="{
                          'warning': elevator.monitorStatus.status === 1,
                          'danger': elevator.monitorStatus.status === 2
                        }"
                      >
                        <div class="elevator-info">
                          <div class="elevator-name">{{ elevator.levelName }}</div>
                          <div class="temperature-range">
                            <span>{{ elevator.monitorStatus.minTemp.toFixed(1) }}~{{ elevator.monitorStatus.maxTemp.toFixed(1) }}°C</span>
                            <span v-if="elevator.monitorStatus.alarmCount > 0" class="alarm-channels">
                              <el-tooltip
                                :content="getElevatorAlarmMessage(elevator)"
                                placement="top"
                              >
                                <el-tag type="danger" size="mini" style="margin-left: 3px;">
                                  {{ elevator.monitorStatus.alarmCount }}
                                </el-tag>
                              </el-tooltip>
                            </span>
                          </div>
                        </div>
                        <div class="elevator-status">
                          <i
                            class="status-icon"
                            :class="{
                              'el-icon-success': elevator.monitorStatus.status === 0,
                              'el-icon-warning': elevator.monitorStatus.status === 1,
                              'el-icon-error': elevator.monitorStatus.status === 2
                            }"
                          ></i>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="monitor-section" style="margin: -8px 0 0 0;">
      <div class="section-title">设备通道实时监测</div>
      <temperature-monitor layout="row" />
    </div>

    <!-- 处理对话框 -->
    <el-dialog :title="handleTitle" :visible.sync="handleOpen" width="500px" append-to-body>
      <el-form ref="handleForm" :model="handleForm" :rules="handleRules" label-width="80px">
        <el-form-item label="处理意见" prop="handledResult">
          <el-input
            v-model="handleForm.handledResult"
            type="textarea"
            placeholder="请输入处理意见"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHandleForm">确 定</el-button>
        <el-button @click="cancelHandle">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOverview } from '@/api/project/monitor';
import { listAlarmEvent, handleEvent } from "@/api/project/event"
import { getMonitorCards } from '@/api/project/building';
import TemperatureMonitor from '@/components/TemperatureMonitor/';


export default {
  name: "Index",
  dicts: ['alarm_type', 'alarm_state'],
  components: {
    // 局部注册组件
    'temperature-monitor': TemperatureMonitor
  },
  data() {
    // 设置默认时间范围（最近一个月）
    const endDate = new Date();
    const startDate = new Date();
    startDate.setMonth(startDate.getMonth() - 1);

    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    return {
      // 版本号
      version: "1.0.0",
      // 加载状态
      loading: false,
      // 总条数
      total: 0,
      // 日期范围（默认最近一个月）
      dateRange: [formatDate(startDate), formatDate(endDate)],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmType: '3',
        eventStatus: 0, // 默认只显示未处理告警
      },
      // 概览数据
      overviewData: {
        deviceCount: 0,
        channelCount: 0,
        meterCount: 0,
        maxTemperature: 0,
        minTemperature: 0,
        temperatureAlarmCount: 0,
        fiberAlarmCount: 0,
        laserFaultCount: 0
      },
      // 告警列表（真实数据）
      alarmList: [],
      // 楼栋监测数据
      buildingData: [],
      unitData: [],
      elevatorData: [],

      // 处理对话框相关数据
      handleOpen: false,
      handleTitle: "",
      currentHandleIds: [],
      handleForm: {
        handledResult: ""
      },
      handleRules: {
        handledResult: [
          { required: true, message: "处理意见不能为空", trigger: "blur" }
        ]
      },
    }
  },
  computed: {
    // 火警报警数量 - 使用真实数据
    fireAlarmCount() {
      return this.overviewData.temperatureAlarmCount || 0
    },
    // 设备报警数量 - 使用真实数据
    deviceAlarmCount() {
      return (this.overviewData.fiberAlarmCount || 0) + (this.overviewData.laserFaultCount || 0)
    },
    // 根据告警类型显示对应的列
    showMeterMark() {
      return !this.queryParams.alarmType || this.queryParams.alarmType == 3;
    },
    showFiberPosition() {
      return !this.queryParams.alarmType || this.queryParams.alarmType == 1;
    },
    showLaserTemp() {
      return !this.queryParams.alarmType || this.queryParams.alarmType == 2;
    },
    showTemperature() {
      return !this.queryParams.alarmType || this.queryParams.alarmType == 3;
    }
  },
  mounted() {
    this.loadOverviewData();
    this.getList();
    this.loadMonitorCards();
  },
  methods: {
    /** 单个处理按钮操作 */
    handleSingleHandle(row) {
      this.currentHandleIds = [row.id];
      this.handleTitle = "处理事件 - " + row.id;
      this.handleForm.handledResult = "";
      this.handleOpen = true;
    },

    /** 提交处理表单 */
    submitHandleForm() {
      this.$refs["handleForm"].validate(valid => {
        if (valid) {
          const handledBy = this.$store.state.user.name;

          // 创建请求数据对象
          const requestData = {
            handledResult: this.handleForm.handledResult,
            handledBy: handledBy
          };

          if (this.currentHandleIds.length === 1) {
            // 单个处理
            requestData.eventId = this.currentHandleIds[0];
            this.handleSingleEvent(requestData);
          }
        }
      });
    },

    /** 处理单个事件 */
    handleSingleEvent(data) {
      // 需要导入 handleEvent API
      handleEvent(data).then(response => {
        this.$modal.msgSuccess("处理成功");
        this.handleOpen = false;
        this.resetHandleForm();
        // 刷新整个首页的所有数据
        this.refreshHomePage();
      }).catch(error => {
        console.error('处理事件失败:', error);
        this.$modal.msgError("处理失败");
      });
    },

    /** 刷新首页所有数据 */
    refreshHomePage() {
      // 显示加载状态
      this.loading = true;

      // 并行刷新所有数据
      Promise.all([
        this.loadOverviewData(),
        this.getList(),
        this.loadMonitorCards()
      ]).then(() => {
        this.loading = false;
        this.$modal.msgSuccess("数据已刷新");
      }).catch(error => {
        this.loading = false;
        console.error('刷新数据失败:', error);
        this.$modal.msgError("刷新数据失败");
      });
    },

    /** 取消处理 */
    cancelHandle() {
      this.handleOpen = false;
      this.resetHandleForm();
    },

    /** 重置处理表单 */
    resetHandleForm() {
      this.handleForm = {
        handledResult: ""
      };
      this.currentHandleIds = [];
      this.resetForm("handleForm");
    },

    /** 加载楼栋监测卡片数据 */
    async loadMonitorCards() {
      try {
        const response = await getMonitorCards();
        if (response && response.code === 200) {
          const data = response.data;
          this.buildingData = data.buildings || [];
          this.unitData = data.units || [];
          this.elevatorData = data.elevators || [];

          // 如果楼栋数量不足4个，补充模拟数据
          if (this.buildingData.length < 4) {
            this.addMockBuildingData();
          }
        } else {
          console.error('获取楼栋监测数据失败:', response?.message);
          // 使用模拟数据
          this.useMockData();
        }
      } catch (error) {
        console.error('加载楼栋监测数据失败:', error);
        // 使用模拟数据
        this.useMockData();
      }
    },

    /** 生成随机温度数据 */
    generateRandomTemp() {
      const baseMin = 23.0;
      const baseMax = 32.5;

      // 生成随机的温度范围，在基础值上下浮动
      const minTemp = baseMin + (Math.random() * 0.5); // 23.0 ~ 23.5
      const maxTemp = baseMax + (Math.random() * 1.5 - 0.5); // 32.0 ~ 34.0
      const currentTemp = minTemp + (Math.random() * (maxTemp - minTemp));

      return {
        minTemp: parseFloat(minTemp.toFixed(1)),
        maxTemp: parseFloat(maxTemp.toFixed(1)),
        currentTemp: parseFloat(currentTemp.toFixed(1))
      };
    },

    /** 补充模拟楼栋数据 */
    addMockBuildingData() {
      const existingCount = this.buildingData.length;
      const needCount = 4 - existingCount;

      for (let i = 1; i <= needCount; i++) {
        const buildingNum = existingCount + i;
        const buildingCode = `SQ-A-${buildingNum}#`;

        // 为楼栋生成随机温度
        const buildingTemp = this.generateRandomTemp();

        // 添加楼栋
        const mockBuilding = {
          lcId: 3000 + buildingNum,
          startMeter: 3000 + (buildingNum - 1) * 1240,
          lcName: `石桥花园-A区-${buildingNum}栋`,
          channelNo: buildingNum,
          level: 3,
          lcDesc: `石桥花园A区${buildingNum}栋`,
          unitCount: 2,
          lcCode: buildingCode,
          levelName: `${buildingNum}栋`,
          deviceNo: "001",
          endMeter: 3000 + buildingNum * 1240,
          monitorStatus: {
            alarmCount: 0,
            statusText: "正常",
            maxTemp: buildingTemp.maxTemp,
            warningFloors: [],
            currentTemp: buildingTemp.currentTemp,
            minTemp: buildingTemp.minTemp,
            status: 0
          }
        };
        this.buildingData.push(mockBuilding);

        // 添加单元
        for (let j = 1; j <= 2; j++) {
          const unitCode = `${buildingCode}-${j}U`;
          // 为单元生成随机温度（与楼栋温度相近但略有差异）
          const unitTemp = this.generateRandomTemp();

          const mockUnit = {
            lcId: 4000 + (buildingNum - 1) * 2 + j,
            lcName: `石桥花园-A区-${buildingNum}栋-${j}单元`,
            channelNo: buildingNum,
            level: 4,
            levelName: `${j}单元`,
            deviceNo: "001",
            elevatorCount: 2,
            startMeter: 3000 + (buildingNum - 1) * 1240 + (j - 1) * 620,
            parentCode: buildingCode,
            lcDesc: `石桥花园A区${buildingNum}栋${j}单元`,
            lcCode: unitCode,
            endMeter: 3000 + (buildingNum - 1) * 1240 + j * 620,
            monitorStatus: {
              alarmCount: 0,
              statusText: "正常",
              maxTemp: unitTemp.maxTemp,
              warningFloors: [],
              currentTemp: unitTemp.currentTemp,
              minTemp: unitTemp.minTemp,
              status: 0
            }
          };
          this.unitData.push(mockUnit);

          // 添加电梯
          for (let k = 1; k <= 2; k++) {
            const elevatorCode = `${unitCode}-${k}#`;
            // 为每部电梯生成独立的随机温度
            const elevatorTemp = this.generateRandomTemp();

            const mockElevator = {
              lcId: 5000 + (buildingNum - 1) * 4 + (j - 1) * 2 + k,
              startMeter: 3000 + (buildingNum - 1) * 1240 + (j - 1) * 620 + (k - 1) * 310,
              lcName: `石桥花园-A区-${buildingNum}栋-${j}单元-${k}号电梯`,
              channelNo: buildingNum,
              level: 5,
              parentCode: unitCode,
              lcDesc: `石桥花园A区${buildingNum}栋${j}单元${k}号电梯`,
              lcCode: elevatorCode,
              levelName: `${k}号电梯`,
              deviceNo: "001",
              endMeter: 3000 + (buildingNum - 1) * 1240 + (j - 1) * 620 + k * 310,
              monitorStatus: {
                alarmCount: 0,
                statusText: "正常",
                maxTemp: elevatorTemp.maxTemp,
                warningFloors: [],
                currentTemp: elevatorTemp.currentTemp,
                minTemp: elevatorTemp.minTemp,
                status: 0
              }
            };
            this.elevatorData.push(mockElevator);
          }
        }
      }
    },

    /** 使用完整的模拟数据 */
    useMockData() {
      // 清空现有数据
      this.buildingData = [];
      this.unitData = [];
      this.elevatorData = [];

      // 添加4个楼栋的完整模拟数据
      for (let buildingNum = 1; buildingNum <= 4; buildingNum++) {
        const buildingCode = `SQ-A-${buildingNum}#`;
        const buildingTemp = this.generateRandomTemp();

        // 添加楼栋
        const mockBuilding = {
          lcId: 1000 + buildingNum,
          startMeter: 1000 + (buildingNum - 1) * 1240,
          lcName: `石桥花园-A区-${buildingNum}栋`,
          channelNo: buildingNum,
          level: 3,
          lcDesc: `石桥花园A区${buildingNum}栋`,
          unitCount: 2,
          lcCode: buildingCode,
          levelName: `${buildingNum}栋`,
          deviceNo: "001",
          endMeter: 1000 + buildingNum * 1240,
          monitorStatus: {
            alarmCount: buildingNum === 1 ? 5 : 0,
            statusText: buildingNum === 1 ? "报警" : "正常",
            maxTemp: buildingNum === 1 ? 65.4 : buildingTemp.maxTemp,
            warningFloors: [],
            currentTemp: buildingNum === 1 ? 65.4 : buildingTemp.currentTemp,
            minTemp: buildingNum === 1 ? 23.3 : buildingTemp.minTemp,
            status: buildingNum === 1 ? 2 : 0
          }
        };
        this.buildingData.push(mockBuilding);

        // 添加单元
        for (let j = 1; j <= 2; j++) {
          const unitCode = `${buildingCode}-${j}U`;
          const unitTemp = this.generateRandomTemp();

          const mockUnit = {
            lcId: 2000 + (buildingNum - 1) * 2 + j,
            lcName: `石桥花园-A区-${buildingNum}栋-${j}单元`,
            channelNo: buildingNum,
            level: 4,
            levelName: `${j}单元`,
            deviceNo: "001",
            elevatorCount: 2,
            startMeter: 1000 + (buildingNum - 1) * 1240 + (j - 1) * 620,
            parentCode: buildingCode,
            lcDesc: `石桥花园A区${buildingNum}栋${j}单元`,
            lcCode: unitCode,
            endMeter: 1000 + (buildingNum - 1) * 1240 + j * 620,
            monitorStatus: {
              alarmCount: (buildingNum === 1 && j === 2) ? 5 : 0,
              statusText: (buildingNum === 1 && j === 2) ? "报警" : "正常",
              maxTemp: (buildingNum === 1 && j === 2) ? 65.4 : unitTemp.maxTemp,
              warningFloors: [],
              currentTemp: (buildingNum === 1 && j === 2) ? 65.4 : unitTemp.currentTemp,
              minTemp: (buildingNum === 1 && j === 2) ? 23.3 : unitTemp.minTemp,
              status: (buildingNum === 1 && j === 2) ? 2 : 0
            }
          };
          this.unitData.push(mockUnit);

          // 添加电梯
          for (let k = 1; k <= 2; k++) {
            const elevatorCode = `${unitCode}-${k}#`;
            const hasAlarm = (buildingNum === 1 && j === 2);
            const elevatorTemp = this.generateRandomTemp();

            const mockElevator = {
              lcId: 3000 + (buildingNum - 1) * 4 + (j - 1) * 2 + k,
              startMeter: 1000 + (buildingNum - 1) * 1240 + (j - 1) * 620 + (k - 1) * 310,
              lcName: `石桥花园-A区-${buildingNum}栋-${j}单元-${k}号电梯`,
              channelNo: buildingNum,
              level: 5,
              parentCode: unitCode,
              lcDesc: `石桥花园A区${buildingNum}栋${j}单元${k}号电梯`,
              lcCode: elevatorCode,
              levelName: `${k}号电梯`,
              deviceNo: "001",
              endMeter: 1000 + (buildingNum - 1) * 1240 + (j - 1) * 620 + k * 310,
              monitorStatus: {
                alarmCount: hasAlarm ? (k === 1 ? 2 : 3) : 0,
                statusText: hasAlarm ? "报警" : "正常",
                maxTemp: hasAlarm ? (k === 1 ? 65.4 : 64.8) : elevatorTemp.maxTemp,
                warningFloors: hasAlarm ? (k === 1 ? ["21L"] : ["4L", "11L"]) : [],
                currentTemp: hasAlarm ? (k === 1 ? 65.4 : 64.8) : elevatorTemp.currentTemp,
                abnormalFloors: hasAlarm ? (k === 1 ? ["B1L"] : ["27L", "28L"]) : [],
                minTemp: hasAlarm ? 23.3 : elevatorTemp.minTemp,
                status: hasAlarm ? 2 : 0
              }
            };
            this.elevatorData.push(mockElevator);
          }
        }
      }
    },

    /** 根据楼栋编码获取对应的单元 */
    getUnitsByBuilding(buildingCode) {
      return this.unitData.filter(unit => unit.parentCode === buildingCode);
    },

    /** 根据单元编码获取对应的电梯 */
    getElevatorsByUnit(unitCode) {
      return this.elevatorData.filter(elevator => elevator.parentCode === unitCode);
    },

    /** 获取电梯告警信息 */
    getElevatorAlarmMessage(elevator) {
      const status = elevator.monitorStatus;
      let message = `${elevator.levelName}，温度：${status.currentTemp.toFixed(1)}°C`;

      if (status.warningFloors && status.warningFloors.length > 0) {
        message += `，预警楼层：${status.warningFloors.join('、')}`;
      }

      if (status.abnormalFloors && status.abnormalFloors.length > 0) {
        message += `，异常楼层：${status.abnormalFloors.join('、')}`;
      }

      if (status.alarmCount > 0) {
        message += `，告警数量：${status.alarmCount}`;
      }

      return message;
    },

    /** 查看告警记录操作 */
    handleViewRecords(row) {
      const queryParams = {
        alarmType: row.alarmType,
        deviceNo: row.deviceNo,
        chanel: row.chanel,
        status: row.status,
        minMeterMark: row.meterMark,
        maxMeterMark: row.meterMark,
        fiberBreakPosition: row.fiberBreakPosition
      }
      this.$router.push({
        path: '/project/record',
        query: queryParams
      })
    },

    // 加载概览数据
    async loadOverviewData() {
      try {
        const response = await getOverview();
        if (response && response.code === 200) {
          const data = response.data;

          // 更新概览数据
          this.overviewData.deviceCount = data.deviceCount || 0;
          this.overviewData.channelCount = data.channelCount || 0;
          this.overviewData.meterCount = data.meterCount || 0;
          this.overviewData.maxTemperature = data.maxTemperature || 0;
          this.overviewData.minTemperature = data.minTemperature || 0;
          this.overviewData.temperatureAlarmCount = data.temperatureAlarmCount || 0;
          this.overviewData.fiberAlarmCount = data.fiberAlarmCount || 0;
          this.overviewData.laserFaultCount = data.laserFaultCount || 0;
        } else {
          console.error('获取概览数据失败:', response?.message);
          // 使用默认数据
          this.setDefaultOverviewData();
        }
      } catch (error) {
        console.error('加载概览数据失败:', error);
        // 使用默认数据
        this.setDefaultOverviewData();
      }
    },

    // 设置默认概览数据
    setDefaultOverviewData() {
      this.overviewData = {
        deviceCount: 24,
        channelCount: 48,
        meterCount: 7200,
        maxTemperature: 52,
        minTemperature: 23,
        temperatureAlarmCount: 2,
        fiberAlarmCount: 1,
        laserFaultCount: 1
      };
    },

    /** 查询告警事件列表 */
    getList() {
      this.loading = true;
      listAlarmEvent(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.alarmList = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        }
      ).catch(error => {
        console.error('获取告警列表失败:', error);
        this.loading = false;
        this.alarmList = [];
        this.total = 0;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      // 重置为最近一个月
      const endDate = new Date();
      const startDate = new Date();
      startDate.setMonth(startDate.getMonth() - 1);

      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      this.dateRange = [formatDate(startDate), formatDate(endDate)];
      this.queryParams.alarmType = undefined;
      this.handleQuery();
    },

    // 时间格式化方法 - 修复版本
    formatTime(time) {
      if (!time) return '-';

      try {
        // 如果是时间戳格式
        if (typeof time === 'number' || (typeof time === 'string' && /^\d+$/.test(time))) {
          time = parseInt(time);
          const date = new Date(time);
          return this.formatDateToDateTime(date);
        }

        // 如果是日期字符串格式
        if (typeof time === 'string') {
          const date = new Date(time);
          if (!isNaN(date.getTime())) {
            return this.formatDateToDateTime(date);
          }
        }

        return time; // 如果无法解析，返回原值
      } catch (error) {
        console.error('时间格式化错误:', error);
        return time;
      }
    },

    // 辅助方法：将Date对象格式化为YYYY-MM-DD HH:mm:ss
    formatDateToDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  .fun-title {
    font-size: 14px;
    font-weight: 500;
  }

  .description {
    font-size: 13px;
    font-weight: 500;
  }

  // 统计卡片样式
  .stat-card {
    text-align: center;
    padding: 10px 6px;
    background: #f8f9fa;
    border-radius: 6px;
    border-left: 4px solid #1890ff;

    &.warning {
      border-left-color: #faad14;
      background: #fff7e6;
    }

    .stat-value {
      font-size: 18px;
      font-weight: bold;
      color: #1890ff;
      margin-bottom: 3px;
    }

    .stat-value.warning {
      color: #f5222d;
    }

    .stat-label {
      font-size: 11px;
      color: #666;
    }
  }

  // 楼栋卡片样式
  .monitor-section {
    margin-bottom: 0;
  }

  .section-title {
    margin: 12px 0;
    padding: 0 12px;
    border-left: 4px solid #1890ff;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
  }

  .building-card {
    transition: all 0.3s;

    &.has-alarm {
      border: 1px solid #ff4d4f;
    }

    .building-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 0 8px 0;
      margin: -4px 0 0 0;
      width: 100%;

      // 确保两个元素都占据空间
      .building-name {
        font-size: 14px;
        font-weight: bold;
        flex: 1; // 占据剩余空间
        margin-right: 8px; // 与标签保持间距
      }

      // 标签保持原有大小
      .el-tag {
        flex-shrink: 0; // 防止标签被压缩
      }
    }

    .unit-section {
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .unit-name.vertical-text {
      writing-mode: vertical-rl;
      text-orientation: mixed;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: 600;
      color: #666;
      border-left: 2px solid #1890ff;
      padding-left: 4px;
      margin-right: 8px;
    }

    .elevator-list {
      .elevator-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px;
        border-radius: 4px;
        border: 1px solid #e8e8e8;
        transition: all 0.3s;
        height: 45px;

        &.warning {
          border-color: #faad14;
          background: #fff7e6;
        }

        &.danger {
          border-color: #ff4d4f;
          background: #fff1f0;
        }

        .elevator-info {
          flex: 1;

          .elevator-name {
            font-weight: bold;
            margin-bottom: 2px;
            font-size: 12px;
          }

          .temperature-range {
            font-size: 10px;
            color: #666;
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            .alarm-channels {
              margin-left: 3px;
            }
          }
        }

        .elevator-status {
          .status-icon {
            font-size: 14px;

            &.el-icon-success {
              color: #52c41a;
            }

            &.el-icon-warning {
              color: #faad14;
            }

            &.el-icon-error {
              color: #ff4d4f;
            }
          }
        }
      }
    }
  }
}
</style>
